
//
// 120328 - AH - (Bergen Off. Bibliotek *) Created.
//

package org.soekrat.server.io.db;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.persistence.Id;

import org.datanucleus.store.mapped.expression.ScalarExpression.IllegalArgumentTypeException;

/**
 * <p>
 *   Binary data described by a
 *   {@link DbFile}.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
public final class DbFileData implements DbObject 
{
  private @Id Long id;
  
  private Long fileId;
  
  private byte[] data;
  
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public DbFileData(){}
  
  /**
   * <p>
   *   Gets unique of key of the fila data.
   * </p>
   * @return Key value or {@code -1} if not assigned (not stored in database).
   */
  public long id(){ return id==null ? -1 : id; }
  
  /**
   * <p>
   *   Gets key of 
   *   {@link DbFile} that has meta data for {@code this}.
   * </p>
   * @return Key value or {@code -1} if not set.
   */
  public long fileId(){ return fileId==null ? -1 : fileId; }
  
  /**
   * <p>
   *   Sets key of 
   *   {@link DbFile} that has meta data for {@code this}.
   * </p>
   * @param id Id to set.
   * @return {@code this}.
   * @throws IllegalArgumentTypeException If {@code id<0}.
   */
  public DbFileData fileId(long id)
  {
    if (id<0)
    {
      throw new IllegalArgumentException("id<0 : "+id);
    }
    
    this.fileId=id;
    
    return this;
  }
  
  /**
   * <p>
   *   Sets binary data.
   * </p>
   * @return Data or {@code null} if does not have.
   */
  public byte[] data(){ return data; }
  
  /**
   * <p>
   *   Gets 
   *   {@link InputStream} to the data.
   * </p>
   * @return Stream.
   */
  public InputStream getInputStream()
  {
    byte[] b=(data==null) ? new byte[0] : data;
    return new ByteArrayInputStream(b);
  }
  
  /**
   * <p>
   *   Sets binary data.
   * </p>
   * @param data Data or {@code null} if do clear.
   * @return {@code this}.
   */
  public DbFileData data(byte[] data){ this.data=data; return this; }
  
}
